package com.freak.wanandroid.model.search.db;

import com.freak.wanandroid.bean.HistoryData;
import com.freak.wanandroid.bean.SystemClassChildrenEntity;
import com.freak.wanandroid.bean.SystemClassifyBean;

import org.litepal.LitePal;

import java.util.List;

/**
 * 数据库操作助手
 * Created by 74099 on 2018/9/6.
 */
public class RealmHelper {
    public void saveHistory(String searchMsg) {
        HistoryData historyData = new HistoryData();
        if (!checkData(searchMsg)) {
            historyData.setData(searchMsg);
            historyData.save();
        }
    }

    public List<HistoryData> selectAllHistory() {
        List<HistoryData> historyDataList = LitePal.findAll(HistoryData.class);
        return historyDataList;
    }

    public boolean checkData(String searchMsg) {
        HistoryData historyData = LitePal.where("data = ?", searchMsg).findFirst(HistoryData.class);
        if (historyData != null) {
            return true;
        } else {
            return false;
        }
    }

    public void clearHistory() {
        LitePal.deleteAll(HistoryData.class);
    }

    public boolean saveSpecialSubscription(List<SystemClassifyBean> list) {
        for (SystemClassifyBean systemClassifyBean : list) {
            LitePal.saveAll(systemClassifyBean.getChildren());
        }
        return LitePal.saveAll(list);
    }

    public List<SystemClassifyBean> getSystemClassify() {
        return LitePal.findAll(SystemClassifyBean.class);
    }

    public List<SystemClassChildrenEntity> getSpecialSubscriptionInfo() {
        return LitePal.where("subscription = ?", "1").find(SystemClassChildrenEntity.class);
    }

    public List<SystemClassChildrenEntity> getSpecialInfo(int parentId) {
        return LitePal.where("subscription = ? and parentChapterId = ?", "0", String.valueOf(parentId)).find(SystemClassChildrenEntity.class);
    }

    public SystemClassChildrenEntity getSpecialSubscriptionInfoByName(String name) {
        return LitePal.where("name = ?", name).findFirst(SystemClassChildrenEntity.class);
    }

    public boolean updateSpecialSubscriptionInfo(SystemClassChildrenEntity classChildrenEntity, int subscription) {
        SystemClassChildrenEntity children = LitePal.
                where("mChildrenId = ?", String.valueOf(classChildrenEntity.getChildrenId()))
                .findFirst(SystemClassChildrenEntity.class);
        children.setSubscription(subscription);
        return children.save();
    }
}
